class ListNode {
    int val;
    ListNode next;

    ListNode() {
    }

    ListNode(int val) {
        this.val = val;
    }

    ListNode(int val, ListNode next) {
        this.val = val;
        this.next = next;
    }
}

public class Java1010 {

    /**
     * 递归反转链表
     */
    public ListNode reverseList(ListNode head) {
        // 递归终止条件：空链表或只有一个节点
        if (head == null || head.next == null) {
            return head;
        }

        // 递归反转后续链表
        ListNode newHead = reverseList(head.next);

        // 将当前节点的下一个节点指向当前节点（反转指针方向）
        head.next.next = head;
        // 断开当前节点的原next指针，防止循环
        head.next = null;

        return newHead;
    }

    /**
     * 打印链表（用于测试）
     */
    public void printList(ListNode head) {
        ListNode current = head;
        while (current != null) {
            System.out.print(current.val + " -> ");
            current = current.next;
        }
        System.out.println("null");
    }

    public static void main(String[] args) {
        System.out.println("1009");

        // 创建测试链表: 1 -> 2 -> 3 -> 4 -> 5
        ListNode head = new ListNode(1);
        head.next = new ListNode(2);
        head.next.next = new ListNode(3);
        head.next.next.next = new ListNode(4);
        head.next.next.next.next = new ListNode(5);

        Java1010 solution = new Java1010();
        System.out.println("原链表:");
        solution.printList(head);

        // 反转链表
        ListNode reversedHead = solution.reverseList(head);

        System.out.println("反转后链表:");
        solution.printList(reversedHead);
    }
}
